<template>
  <div class="run-modal-style" style="height: 460px;">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="userSearchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 用户账号 -->
        <Form-item prop="account" :label="$t('module.userManage.account')">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.account"
            :placeholder="$t('module.userManage.warning.enterUserAccount')"
            
            @on-enter="search"
          ></Input>
        </Form-item>
        <!-- 用户名称 -->
        <Form-item prop="userName" :label="$t('module.userManage.name')">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.userName"
            :placeholder="$t('module.userManage.warning.enterUserName')"
            
            @on-enter="search"
          ></Input>
        </Form-item>
        <!-- 所属组织 -->
        <Form-item prop="orgName" :label="$t('module.userManage.organization')">
          <Input
            type="text"
            style="position: absolute; z-index: 999; opacity: 0; width: 80%;"
            @click.native="selectOrganization"
          ></Input>
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.orgName"
            :placeholder="$t('module.userManage.selectOrganization')"
            
            icon="ios-paper-plane-outline"
            clearable
            readonly
            @on-click="selectOrganization"
            @on-clear="clearSearchForm"
          ></Input>
        </Form-item>

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" @click="search" />
          <RPButton optType="reset" @click="reset" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="userTable" :config="tableConfig">
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="reset" />
      </div>
      -->
    </InnerPageTable>
  </div>
</template>
<script>
import orgAssignRoleAPI from "@/api/orgAssignRoleAPI.js";
import locales from "./locales.js";
import { roleSelectUserColumns } from "./columns.js";
import appAssignUserAPI from "@/api/appAssignUserAPI.js";
import { searchAppList } from "@/api/applicationApi.js";
import selectOrg from "../userCenter/userManage/selectOrganization.vue";
import { queryOrgsByOrgPaths } from "@/api/orgApi";

export default {
  name: "role-select-user",
  mixins: [locales],
  props: {
    tenantCode: {
      type: String,
      default() {
        return "";
      }
    },
    orgId: {
      type: String,
      default() {
        return "";
      }
    },
    roleId: {
      type: String,
      default() {
        return "";
      }
    },
    orgRoleId: {
      type: String,
      default() {
        return "";
      }
    },
    roleCode: {
      type: String,
      default() {
        return "";
      }
    },
    orgName: String,
    roleName: String
  },
  data() {
    return {
      searchForm: {
        tenantCode: this.tenantCode,
        roleId: this.roleId,
        account: "",
        userId: "",
        userName: "",
        orgRoleId: this.orgRoleId,
        orgName: "",
        orgPath: ""
      },
      actions: [
        {
          text: this.$t("common.confirm"),
          theme: "primary",
          handle: () => {
            this.onSaveClick();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {
    tableConfig() {
      return {
        loadDataFn: ({ responseProcess, param, tableData }) => {
          orgAssignRoleAPI.queryUnassignedUser(param).then(data => {
            let orgPaths = data.records.map(user => {
              return user.orgPath;
            });

            queryOrgsByOrgPaths(orgPaths).then(orgs => {
              data.records.forEach(user => {
                let userOrg = orgs.find(org => {
                  return org.orgPath == user.orgPath;
                });
                user._hasOrgInfo = true;
                if (userOrg) {
                  user.orgName = userOrg.orgName;
                  user.orgNameFullPath = userOrg.orgNameFullPath;
                } else {
                  user.orgName = user.orgPath;
                  user.orgNameFullPath = user.orgPath;
                }
              });
              tableData = data.records;
              responseProcess(data);
            });
            responseProcess(data);
          });
        },
        autoFirst: true,
        columnsFn: roleSelectUserColumns.bind(this),
        initParam: this.searchForm
      };
    }
  },
  created: function() {
    this.$emit("SetTitle", this.$t("module.post.selectUser"));
    this.$emit("SetPageWidth", 850);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    selectOrganization() {
      new this.$pageModal(
        selectOrg,
        {
          props: {}
        },
        data => {
          if (data) {
            this.searchForm.orgPath = data.orgPath;
            this.searchForm.orgName = data.orgName;
          }
        }
      );
    },
    clearSearchForm() {
      this.searchForm.orgPath = "";
      this.searchForm.orgName = "";
    },
    search(page) {
      this.searchForm.userId = this.searchForm.account;
      this.$refs["userTable"].load(this.searchForm, page);
    },
    reset() {
      this.$refs["userSearchForm"].resetFields();
      this.searchForm.orgPath = "";
      this.search(1);
    },
    onSaveClick() {
      // 如果未勾选，无需保存
      let { ids: selectedIds, adminIds } = this.getSelectedIds();
      if (selectedIds.length == 0) {
        this.$message.error({
          content: this.$t("module.role.warning.selectUsers"),
          duration: 3
        });
        return;
      }
      this.actions[0].loading = true;
      // 判断用户是否已分配给其它角色
      if (selectedIds.length > 1) {
        let mess = `${this.$t("module.userManage.confircurusermassign")}  ${this.orgName}-${this.roleName}  ${this.$t(
          "module.userManage.role"
        )}`;
        this.$confirm
          .warning(mess)
          .then(() => {
            this.toSave(selectedIds);
          })
          .catch(() => {
            this.actions[0].loading = false;
          });
      } else {
        orgAssignRoleAPI.getAssignedUserRole(selectedIds).then(data => {
          let message = "";
          for (const key in data) {
            if (data.hasOwnProperty(key)) {
              let infos = [];
              const roles = data[key];

              // 过滤当前用户是否已分配过该角色
              if (roles && roles.length > 0) {
                let result = [];
                result = roles.filter(item => {
                  return item.roleCode === this.roleCode;
                });
                let orgList = [];
                result.forEach(item => {
                  orgList.push(item.orgName);
                });
                if (result && result.length > 0) {
                  message = `${this.$t("module.userManage.currentUserhas")}  ${orgList.toString()}  ${this.$t(
                    "module.userManage.alreadyassign"
                  )}  ${result[0].roleName}, ${this.$t("module.userManage.confirmassign")}  ${this.orgName}-${
                    this.roleName
                  }  ${this.$t("module.userManage.role")}`;
                }
              }
            }
          }
          if (message == "") {
            let mess = `${this.$t("module.userManage.confircurusermassign")}  ${this.orgName}-${
              this.roleName
            }  ${this.$t("module.userManage.role")}`;
            this.$confirm
              .warning(mess)
              .then(() => {
                this.toSave(selectedIds);
              })
              .catch(() => {
                this.actions[0].loading = false;
              });
          } else {
            this.$confirm
              .warning(message)
              .then(() => {
                this.toSave(selectedIds);
              })
              .catch(() => {
                this.actions[0].loading = false;
              });
          }
        });
      }
    },
    getSelectedIds() {
      let list = this.$refs["userTable"].getSelectioned() || [];
      let ids = [];
      // 管理员
      let adminIds = [];
      for (let { id, category } of list) {
        ids.push(id);
        // 为管理员时
        if (category == 1 || category == 2) {
          adminIds.push(id);
        }
      }
      return { ids, adminIds };
    },
    toSave(selectedIds) {
      let param = {
        orgRoleId: this.orgRoleId,
        userIds: selectedIds,
        roleId: this.roleId
      };
      orgAssignRoleAPI.saveAssignedUser(param).then(data => {
        // this.appAssignedUser(selectedIds);需求变更，该逻辑改到后端处理。
        this.$message.success({
          content: this.$t("module.role.warning.assignUserSuccessfully"),
          duration: 3
        });
        this.$emit("Close", true);
      });
    },
    appAssignedUser(selectedIds) {
      // 预置角色分配用户时，关联到应用
      if ((this.roleCode == "admin-dadp" || this.roleCode == "admin-tenant") && selectedIds.length > 0) {
        // 获取数字化应用
        searchAppList({ pageNum: 1, pageSize: 200 }).then(({ data: { records } }) => {
          let app = records.find(app => {
            return app.clientId == "RIPPLES.crc";
          });
          if (app) {
            let param = {
              userApplicationInfoVo: {
                applicationCode: app.clientId,
                applicationId: app.id,
                applicationType: 0,
                applicationName: app.appName
              },
              userIds: selectedIds
            };
            appAssignUserAPI.saveAssignedUser(param);
          }
        });
      }
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less">
.run-modal-style {
  .ivu-input-icon {
    cursor: pointer;
    font-size: 16px !important;
    line-height: 34px !important;
    cursor: pointer;
    -moz-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    transform: scaleX(-1);
    /*IE*/
    filter: FlipH;
  }
  .ivu-spin {
    text-align: left;
  }
  .spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }
}
</style>
